package com.gitee.maskit.onecloud;

import de.codecentric.boot.admin.config.AdminServerProperties;
import de.codecentric.boot.admin.config.EnableAdminServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;

/**
 * @author z0228
 */
@SpringCloudApplication
@EnableConfigServer
@EnableEurekaServer
@EnableAutoConfiguration
@EnableAdminServer
@EnableDiscoveryClient
public class OneCloudApplication {

    @Configuration
    @ConditionalOnProperty(prefix = "security", name = "basic.enabled", havingValue = "true")
    public static class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private AdminServerProperties admin;

        private String path(String origin) {
            return null != admin.getContextPath() ?
                admin.getContextPath() + origin : origin;
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // Page with login form is served as /login.html and does a POST on /login
            http.formLogin()
                .loginPage(path("/login.html"))
                .loginProcessingUrl("/login")
                .permitAll();
            // The UI does a POST on /logout on logout
            http.logout().logoutUrl("/logout");
            // The ui currently doesn't support csrf
            http.csrf().disable();

            // Requests for the login page and the static assets are allowed
            http.authorizeRequests()
                .antMatchers(
                    path("/login.html"),
                    path("/**/*.css"),
                    path("/img/**"),
                    path("/third-party/**"))
                .permitAll();
            // ... and any other request needs to be authorized
            http.authorizeRequests().antMatchers("/**").authenticated();

            // Enable so that the clients can authenticate via HTTP basic for registering
            http.httpBasic();
        }
    }

    public static void main(String[] args) throws IOException {
        final String encoding = System.getProperties().getProperty("file.encoding");
        final String osEncoding = System.getProperties().getProperty("sun.jnu.encoding");

        Arrays.asList(
            "《编码：" + encoding + "/" + osEncoding + "》",
            "如果您希望启用加密，请前往下列地址下载JCE：",
            "http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html",
            "并将全部JAR文件解压到" + (System.getProperties().containsKey("java.home") ?
                Paths.get(System.getProperties().getProperty("java.home"), "lib", "security") :
                "${JAVA_HOME}/lib/security/") + "目录下替换原文件，",
            "然后指定密码重启本应用：java -Dencrypt.key=<password> -Dgit.user=<username> -jar onecloud.jar ..."
        ).forEach(ln -> {
            try {
                System.out.write(ln.getBytes(encoding));
                System.out.println("");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        final String user = System.getProperties().getProperty("git.user",
            System.getProperties().getProperty("user.name"));

        System.getProperties().put("git.user", user);

        SpringApplication.run(OneCloudApplication.class, args);
    }
}
